import os
import fitz

def batch_stretch_pdf(source_dir, target_dir, x_scale=1.2):
    """
    批量横向拉伸PDF文件
    :param source_dir: 源目录路径
    :param target_dir: 目标目录路径
    :param x_scale: 横向拉伸比例
    """
    # 预检PDF文件
    pdf_files = [f for f in os.listdir(source_dir) if f.lower().endswith('.pdf')]
    total = len(pdf_files)
    
    if not pdf_files:
        print("⚠️ 未找到PDF文件")
        return

    # 创建输出目录
    os.makedirs(target_dir, exist_ok=True)
    
    print(f"📁 发现 {total} 个PDF文件")
    print("🔄 开始转换...\n")

    success = 0
    errors = []

    for index, filename in enumerate(pdf_files):
        current_num = index + 1
        progress = current_num / total * 100
        input_path = os.path.join(source_dir, filename)
        output_path = os.path.join(target_dir, filename)
        
        # 进度显示
        status_line = f"[{current_num}/{total} {progress:.1f}%] 正在处理 {filename}"
        print(status_line.ljust(80), end='\r')

        try:
            # 执行拉伸转换
            _stretch_single_pdf(input_path, output_path, x_scale)
            success += 1
            print(f"✅ [{current_num}/{total}] 转换成功: {filename}".ljust(80))
        except Exception as e:
            error_msg = f"❌ [{current_num}/{total}] 转换失败: {filename} - {str(e)}"
            print(error_msg.ljust(80))
            errors.append(error_msg)

    # 最终统计
    print("\n\n转换完成:")
    print(f"✓ 成功: {success} 个")
    print(f"✗ 失败: {len(errors)} 个")
    
    if errors:
        print("\n错误详情:")
        for error in errors:
            print(f"  {error}")

def _stretch_single_pdf(input_path, output_path, x_scale):
    """处理单个PDF文件的核心函数"""
    src_doc = fitz.open(input_path)
    dst_doc = fitz.open()
    
    try:
        for page_num in range(len(src_doc)):
            src_page = src_doc[page_num]
            
            # 计算新页面尺寸
            original_width = src_page.rect.width
            original_height = src_page.rect.height
            new_width = original_width * x_scale
            
            # 创建新页面
            dst_page = dst_doc.new_page(width=new_width, height=original_height)
            
            # 执行内容拉伸
            src_rect = src_page.rect
            dst_rect = fitz.Rect(0, 0, new_width, original_height)
            
            dst_page.show_pdf_page(
                dst_rect,
                src_doc,
                page_num,
                clip=src_rect,
                keep_proportion=False
            )
        
        # 保存文档
        dst_doc.save(output_path)
    finally:
        src_doc.close()
        dst_doc.close()

if __name__ == "__main__":
    # 使用示例
    batch_stretch_pdf(
        source_dir="./pdfs",    # 源PDF目录
        target_dir="./output",  # 输出目录
        x_scale=1.2            # 横向拉伸比例（1.2表示横向拉伸20%）
    )